from fastapi import APIRouter, Depends, Request, Form
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from . import models, utils
from auth.utils import get_current_user_info
from datetime import datetime, timedelta, timezone
from .db import SessionLocal
from logging_config import setup_logging
logger=setup_logging()
router = APIRouter()
templates = Jinja2Templates(directory="templates")
# ---------------- 数据库连接 ----------------
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
# ---------------- 时区修改 ----------------
CST = timezone(timedelta(hours=8))
def now_cst():
    """返回当前北京时间（带时区信息）"""
    return datetime.now(CST)

# 查看个人信息
# ---------------- 个人信息页 ----------------
@router.get("/profile", response_class=HTMLResponse)
def profile_page(request: Request, db: Session = Depends(get_db)):
    username, role = get_current_user_info(request)
    if not username:
        return RedirectResponse(url="/login", status_code=303)
    user = db.query(models.User).filter(models.User.username == username).first()

    doctor_name = None
    if user.role == "user" and user.doctor_id:
        doctor = db.query(models.User).filter(models.User.id == user.doctor_id).first()
        doctor_name = doctor.username if doctor else "未指定"
    logger.info(f"{user}查看个人信息")
    return templates.TemplateResponse("dashboard.html", {
        "request": request, "username": username, "role": role,
        "user": user, "doctor_name": doctor_name, "active_tab": "profile"
    })
# 修改个人信息
# ---------------- 修改个人信息 ----------------
@router.post("/profile/update")
def update_profile(
    request: Request,
    email: str = Form(""),
    phone: str = Form(""),
    password: str = Form(""),
    db: Session = Depends(get_db)
):
    """修改个人信息：符合测试规则 + 特殊规则
       邮箱为空表示清空，手机号为空表示不修改
    """
    username, role = get_current_user_info(request)
    if not username:
        return RedirectResponse(url="/login", status_code=303)

    user = db.query(models.User).filter(models.User.username == username).first()
    if not user:
        return RedirectResponse(url="/login", status_code=303)

    import re
    email = (email or "").strip()
    phone = (phone or "").strip()
    password = (password or "").strip()

    changed = False

    # ---------- 邮箱逻辑 ----------
    if email == "":
        # 空邮箱表示清空（如果原来有邮箱）
        if user.email not in [None, ""]:
            user.email = None
            changed = True
    else:
        email_pattern = r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$"
        if not re.match(email_pattern, email):
            return HTMLResponse("<script>alert('邮箱格式不正确！');history.back();</script>")

        # 邮箱唯一性检查
        existing_email = db.query(models.User).filter(
            models.User.email == email, models.User.username != username
        ).first()
        if existing_email:
            return HTMLResponse("<script>alert('该邮箱已被使用！');history.back();</script>")

        # 大小写不区分
        if email.lower() != (user.email or "").lower():
            user.email = email
            changed = True

    # ---------- 手机号逻辑 ----------
    # 空手机号表示“不修改”
    if phone != "":
        phone_pattern = r"^1[3-9]\d{9}$"
        if not re.match(phone_pattern, phone):
            return HTMLResponse("<script>alert('手机号格式不正确！');history.back();</script>")

        existing_phone = db.query(models.User).filter(
            models.User.phone == phone, models.User.username != username
        ).first()
        if existing_phone:
            return HTMLResponse("<script>alert('该手机号已被使用！');history.back();</script>")

        if phone != (user.phone or ""):
            user.phone = phone
            changed = True

    # ---------- 密码逻辑 ----------
    # 空密码表示不修改
    if password:
        if len(password) < 6 or len(password) > 13:
            return HTMLResponse("<script>alert('密码长度必须在 6 到 13 个字符之间！');history.back();</script>")

        pwd_pattern = r"^[A-Za-z0-9@#$%^&+=]+$"
        if not re.match(pwd_pattern, password):
            return HTMLResponse("<script>alert('密码只能包含字母、数字和 @#$%^&+= 符号！');history.back();</script>")

        # 仅当与原密码不一致时修改
        if not utils.verify_password(password, user.password):
            user.password = utils.hash_password(password)
            changed = True

    # ---------- 未修改 ----------
    if not changed:
        return HTMLResponse("""
            <script>
                alert("未修改任何个人信息");
                history.back();
            </script>
        """)

    # ---------- 提交 ----------
    db.add(user)
    db.commit()
    db.refresh(user)
    logger.info(f"{user}修改个人信息")
    return HTMLResponse("""
        <script>
            alert("修改成功！");
            window.location.href = '/profile';
        </script>
    """)

